<?php

namespace Client\Controller;

use Org\Net\Http;
use Think\Image;
use Think\Controller;

header ( "Content-type: text/html; charset=utf-8" );
/**
 * 约吧信息页
 * 
 * @author dwj
 *        
 */
class PublishController extends Controller {
	/**
	 * 添加位置信息
	 */
	public function addLocation() {
		$http = new Http ();
		$post ['latitude'] = $_POST ['latitude'];
		$post ['longitude'] = $_POST ['longitude'];
		$post ['geotable_id'] = C ( 'BAIDU_LOCATION' );
		$post ['ak'] = C ( "BAIDU_AK" );
		$post ['coord_type'] = 3;
		$post ['address'] = $_POST ['address'];
		$post ['title'] = $_POST ['title'];
		$data ['post'] = $post;
		$back = $http->fsockopenDownload ( C ( "BAIDU_POI_CREATE" ), $data );
		// file_put_contents("Public/Log/log.txt", "back:".$back."\r\n",FILE_APPEND|LOCK_EX);
		$back = json_decode ( $back, 'json' );
		if ($back ['status'] == 0) {
			$json ['result'] = 0;
			$json ['msg'] = "添加位置信息成功";
		} else {
			$json ['result'] = - 1;
			$json ['msg'] = "添加位置信息失败";
		}
		$this->ajaxReturn ( $json );
	}
	/**
	 * 获取附近的位置信息
	 */
	public function getLocation() {
		$http = new Http ();
		$location = I ( 'longitude' ) . ',' . I ( 'latitude' );
		$pageSize = 10;
		$page = I ( 'page' );
		if (! isset ( $page )) {
			$page = 0;
		}
		$geotable_id = C ( 'BAIDU_LOCATION' );
		$url = C ( 'BAIDU_GEOSEARCH' ) . "?ak=" . C ( 'BAIDU_AK' ) . "&sortby=distance:1&geotable_id={$geotable_id}&location={$location}&page_size={$pageSize}&page_index={$page}";
		$result = $http->fsockopenDownload ( $url );
		$list = json_decode ( $result, 'json' );
		$contents = $list ['contents'];
		if ($list ['size'] > 0) {
			$locs = array ();
			foreach ( $list as $contents ) {
				$loc ['title'] = $poi ['title'];
				$loc ['longitude'] = $poi ['location'] [0];
				$loc ['latitude'] = $poi ['location'] [1];
				$locs [] = $loc;
			}
			if (sizeof ( $locs ) > 0) {
				$json ['result'] = 0;
				$json ['msg'] = "获取位置信息成功";
				$json ['locs'] = $locs;
			}
		} else {
			$json ['result'] = - 1;
			$json ['msg'] = "暂无更多附近位置信息";
		}
		$this->ajaxReturn ( $json );
	}
	/**
	 * 添加约吧信息
	 */
	public function savePublish() {
		if (IS_POST) {
			file_put_contents ( "Public/Log/log.txt", "post:" . json_encode ( $_POST ) . "\r\n", FILE_APPEND | LOCK_EX );
			$http = new Http ();
			$post ['latitude'] = $_POST ['latitude'];
			$post ['longitude'] = $_POST ['longitude'];
			$post ['geotable_id'] = C ( 'BAIDU_PUBLISH' );
			$post ['ak'] = C ( "BAIDU_AK" );
			$post ['coord_type'] = 3;
			$post ['address'] = $_POST ['address'];
			$post ['title'] = $_POST ['content'];
			// $post ['tags'] = $_POST ['tag'];
			$data ['post'] = $post;
			$back = $http->fsockopenDownload ( C ( "BAIDU_POI_CREATE" ), $data );
			file_put_contents ( "Public/Log/log.txt", "back:" . $back . "\r\n", FILE_APPEND | LOCK_EX );
			$back = json_decode ( $back );
			
			if ($back->status == 0) {
				$files = $_FILES;
				$publish_info ['address'] = $_POST ['address'];
				$publish_info ['content'] = I ( 'content' );
				$publish_info ['time'] = I ( 'time' );
				$publish_info ['aid'] = I ( 'aid' );
				$publish_info ['tag'] = I ( 'tag' );
				$publish_info ['related_destination'] = I ( 'relatedDestination' );
				$publish_info ['poi_id'] = $back->id;
				$image_url = '';
				$data ["code"] = 0;
				foreach ( $files as $file ) {
					$uploadpath = "Public/uploads/Yue/{$publish_info ['aid']}/"; // 上传路径
					
					$util = A ( 'Util' );
					$util->createDir ( $uploadpath ); // 上传路径是否已经存在，不存在则创建
					
					$pinfo = pathinfo ( $file ['name'] );
					$ftype = $pinfo ['extension']; // 文件类型
					$name = basename ( $file ['name'], ".{$ftype}" );
					
					$fileName = md5 ( $name . time () ) . "_{$data["code"]}." . $ftype; // 识别图
					$image = new Image ();
					$image->open ( $file ['tmp_name'] );
					if ($file ['size'] < 1048576) {
						$image->save ( $uploadpath . $fileName );
					}
					$data ["image"] [] = 'http://' . $_SERVER ['HTTP_HOST'] . '/' . __ROOT__ . '/' . $uploadpath . $fileName;
					$image_url .= 'http://' . $_SERVER ['HTTP_HOST'] . '/' . __ROOT__ . '/' . $uploadpath . $fileName . ",";
					$data ["code"] ++;
				}
				$publish_info ['image'] = substr ( $image_url, 0, strlen ( $image_url ) - 1 );
				$publish = D ( "Publish" );
				// file_put_contents("Public/Log/log.txt", "publish_info:".json_encode($publish_info)."\r\n",FILE_APPEND|LOCK_EX);
				$data = $publish->create ( $publish_info );
				if ($data) {
					// file_put_contents("Public/Log/log.txt", "data:".json_encode($data)."\r\n",FILE_APPEND|LOCK_EX);
					$publish->add ( $data );
					$json ['result'] = 0;
					$json ['msg'] = '发布成功';
				} else {
					$json ['result'] = - 1;
					$json ['msg'] = $publish->getError ();
				}
			} else {
				$json ['result'] = - 2;
				$json ['msg'] = $back->message;
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 刷新约吧信息
	 */
	public function refreshPublish() {
		S ( 'publish_list', null );
		$this->getPublish ();
	}
	/**
	 * 获取约吧信息
	 */
	public function getPublish() {
		$list = S ( 'publish_list' );
		$pageSize = 10;
		$page = I ( 'page' );
		if (isset ( $page )) {
			$start = $page * $pageSize;
		}
		$sex = I ( 'sex' ); // 性别
		if ($sex && $sex != 0) {
			$where ['Account.sex'] = $sex;
		}
		if (! $list) {
			$publish = D ( 'PublishView' );
			
			$list = $publish->where ( $where )->cache ( 'publish_list' )->order ( 'ctime desc' )->select ();
		}
		$res = array_slice ( $list, $start, $pageSize );
		if (count ( $res ) > 0) {
			$json ['result'] = 0;
			$json ['msg'] = "成功获取约吧信息";
			$json ['publish'] = $res;
		} else {
			$json ['result'] = - 1;
			$json ['msg'] = "暂无更多的约吧信息";
		}
		$this->ajaxReturn ( $json );
	}
	/**
	 * 获取附近的约吧信息
	 */
	public function getNearby() {
		$http = new Http ();
		$publish = D ( 'PublishView' );
		$pageSize = 10;
		$page = I ( 'page' );
		if (! isset ( $page )) {
			$page = 0;
		}
		$sex = I ( 'sex' ); // 性别
		if ($sex && $sex != 0) {
			$w ['Account.sex'] = $sex;
		}
		// $location = I ( 'location' );
		$location = I ( 'longitude' ) . ',' . I ( 'latitude' );
		$geotable_id = C ( 'BAIDU_PUBLISH' );
		$url = C ( 'BAIDU_GEOSEARCH' ) . "?ak=" . C ( 'BAIDU_AK' ) . "&sortby=distance:1&geotable_id={$geotable_id}&location={$location}&radius=3000&page_size={$pageSize}&page_index={$page}";
		$result = $http->fsockopenDownload ( $url );
		$res = json_decode ( $result, 'json' );
		// var_dump($res);
		$where = array ();
		if ($res ['size'] > 0) {
			foreach ( $res ['contents'] as $obj ) {
				$poi_id = $obj ['uid'];
				array_push ( $where, $poi_id );
			}
			$w ['poi_id'] = array (
					"in",
					$where 
			);
			$resu = $publish->where ( $w )->select ();
			if (sizeof ( $resu ) > 0) {
				$json ['result'] = "0";
				$json ['msg'] = "获取成功";
				$json ['publish'] = $resu;
			} else {
				$json ['result'] = "-1";
				$json ['msg'] = $publish->getError ();
			}
		} else {
			$json ['result'] = "-2";
			$json ['msg'] = '无法检索到附近的用户';
		}
		
		$this->ajaxReturn ( $json );
	}
	/**
	 * 获取用户的约吧信息
	 */
	public function getPublishById() {
		$id = I ( 'id' );
		$list = S ( 'publish_' . $id );
		$pageSize = 10;
		$page = I ( 'page' );
		if (isset ( $page )) {
			$start = $page * $pageSize;
		}
		if (! $list) {
			$publish = D ( 'PublishView' );
			$list = $publish->cache ( 'publish_' . $id )->order ( 'ctime desc' )->select ();
		}
		$res = array_slice ( $list, $start, $pageSize );
		if (count ( $res ) > 0) {
			$json ['result'] = 0;
			$json ['msg'] = "成功获取约吧信息";
			$json ['publish'] = $res;
		} else {
			$json ['result'] = - 1;
			$json ['msg'] = "暂无更多的约吧信息";
		}
		$this->ajaxReturn ( $json );
	}
	/**
	 * 下拉刷新约吧，获取约吧的最新前十条信息
	 */
	public function reflashPublish() {
		S ( 'result', null );
		$publish = D ( 'PublishView' );
		$result = $publish->limit ( 0, 10 )->order ( array (
				'ctime' => 'desc' 
		) )->select ();
		if (sizeof ( $result ) > 0) {
			$json ['result'] = "0";
			$json ['msg'] = "获取成功";
			foreach ( $result as $k => $v ) {
				$result [$k] ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
			}
			$json ['publish'] = $result;
			$this->ajaxReturn ( $json );
		} else {
			$this->ajaxReturn ( array (
					'msg' => '没有更多的信息了',
					'result' => '-1' 
			), 'json' );
		}
	}
	/**
	 * 筛选
	 */
	public function filtratePublish() {
		if (IS_POST) {
			$pageSize = 10;
			$page = I ( 'page' ); // 页数
			$area = I ( 'area' ); // 区域
			$sex = I ( 'sex' ); // 性别
			$string = "publish_filtrate_{$area}_{$sex}"; // 缓存的Key
			/*
			 * 若为附近则在Key上加上经纬度()
			 */
			if ($area == 'Nearby') {
				$location = I ( 'longitude' ) . ',' . I ( 'latitude' );
				$string .= "{$string}_{$location}";
			}
			if ($page) {
				$start = $page * $pageSize;
			} else {
				S ( $string, null );
			}
			$list = S ( $string );
			if (! $list) {
				if ($sex) { // 性别参数若存在且不为0;则作为搜索参数
					$where ['Account.sex'] = $sex;
				}
				$publish = D ( 'PublishView' );
				if ($area && $area == 'Nearby') { // 是否是附近的人
					$http = new Http ();
					// $location = I ( 'location' );
					$location = I ( 'longitude' ) . ',' . I ( 'latitude' );
					$geotable_id = C ( 'BAIDU_PUBLISH' );
					$url = C ( 'BAIDU_GEOSEARCH' ) . "?ak=" . C ( 'BAIDU_AK' ) . "&sortby=distance:1&geotable_id={$geotable_id}&location={$location}&radius=3000&page_size=200";
					$result = $http->fsockopenDownload ( $url );
					$res = json_decode ( $result, 'json' );
					// var_dump($res);
					$w = array ();
					if ($res ['size'] > 0) {
						foreach ( $res ['contents'] as $obj ) {
							$poi_id = $obj ['uid'];
							array_push ( $w, $poi_id );
						}
						$where ['poi_id'] = array (
								"in",
								$w 
						);
					}
				}
				$list = $publish->cache ( $string )->where ( $where )->order ( 'ctime desc' )->select ();
			}
			$res = array_slice ( $list, $start, $pageSize );
			$count = count ( $res );
			if ($count > 0) {
				$json ['result'] = 0;
				$json ['msg'] = "成功获取约吧信息";
				$aid = I ( 'aid' );
				if ($aid) { // 用户ID是否存在
					$where2 ['aid'] = I ( 'aid' );
					for($i = 0; $i < $count; $i ++) {
						$where2 ['pid'] = $res [$i] ['id'];
						if (M ( 'PublishDate' )->where ( $where2 )->count ()) {
							$res [$i] ['is_dated'] = TRUE;
						} else {
							$res [$i] ['is_dated'] = FALSE;
						}
					}
				} else {
					for($i = 0; $i < $count; $i ++) {
						$res [$i] ['is_dated'] = FALSE;
					}
				}
				$json ['publish'] = $res;
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = "暂无更多的约吧信息";
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 修改约（尚未约则创建，若已约则删除该信息）
	 */
	public function changDate() {
		if (IS_POST) {
			$where ['pid'] = I ( 'pid' );
			$where ['aid'] = I ( 'aid' );
			$is_dated = I ( 'is_dated' );
			$pd = D ( 'PublishDate' );
			if ($is_dated) {
				$json ['msg'] = "取消约";
				$result = $pd->where ( $where )->delete ();
			} else {
				$json ['msg'] = "添加约";
				$data = $pd->create ( $where );
				if ($data) {
					$result = $pd->add ( $data );
				} else {
					$this->ajaxReturn ( array (
							'result' => - 2,
							'msg' => $pd->getError () 
					) );
				}
			}
			if ($result) {
				$json ['result'] = 0;
				$json ['msg'] .= "成功";
			} else {
				$json ['result'] = - 1;
				$json ['msg'] .= "失败";
			}
			$this->ajaxReturn ( $json );
		}
	}
	public function searchPublish() {
		if (IS_POST) {
			$search = $_POST ['searchContent'];
			$publish = D ( 'PublishView' );
			$result = $publish->where ( "content regexp '" . $search . "' or Publish.address regexp '" . $search . "' or tag regexp '" . $search . "'" )->order ( array (
					'ctime' => 'desc' 
			) )->select ();
			$scenic = M ( 'Scenic' )->where ( "name regexp '" . $search . "' or address regexp '" . $search . "' or intro regexp '" . $search . "' or type regexp '" . $search . "'" )->select ();
			$where ['name'] = array (
					'like',
					"%{$search}%" 
			);
			$where ['type'] = 0;
			$tickets = D ( 'ScenicTicket' );
			$ticket = $tickets->relation ( true )->where ( $where )->select ();
			$where2 ['name'] = array (
					'like',
					"%{$search}%" 
			);
			$where2 ['type'] = 1;
			$entertainment = $tickets->relation ( true )->where ( $where2 )->select ();
			// $entertainment = M('ScenicTicket')->where("name regexp '".$search."'")->select();
			// $entertainment = array();
			if (sizeof ( $result ) > 0 || sizeof ( $scenic ) > 0 || sizeof ( $ticket ) > 0 || sizeof ( $entertainment ) > 0) {
				foreach ( $result as $k => $v ) {
					$result [$k] ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
				}
				$ticketres = array ();
				foreach ( $ticket as $k => $v ) {
					$ticketres [$k] ['ticket_time'] = date ( 'Y-m-d H:i:s', $v ['time'] );
					$ticketres [$k] ['ticket_id'] = $v ['id'];
					$ticketres [$k] ['ticket_name'] = $v ['name'];
					$ticketres [$k] ['ticket_price'] = $v ['price'];
					$ticketres [$k] ['ticket_deadline'] = $v ['deadline'];
					$ticketres [$k] ['ticket_original'] = $v ['original'];
					$ticketres [$k] ['ticket_image'] = $v ['image'];
					$ticketres [$k] ['scenic_image'] = $v ['scenic_image'];
					$ticketres [$k] ['scenic_id'] = $v ['scenic_id'];
					$ticketres [$k] ['scenic_name'] = $v ['scenic_name'];
					$ticketres [$k] ['scenic_address'] = $v ['scenic_address'];
					$ticketres [$k] ['scenic_latitude'] = $v ['scenic_latitude'];
					$ticketres [$k] ['scenic_longitude'] = $v ['scenic_longitude'];
					$ticketres [$k] ['scenic_phone'] = $v ['scenic_phone'];
				}
				$entertainmentres = array ();
				foreach ( $entertainment as $k => $v ) {
					$entertainmentres [$k] ['ticket_time'] = date ( 'Y-m-d H:i:s', $v ['time'] );
					$entertainmentres [$k] ['ticket_id'] = $v ['id'];
					$entertainmentres [$k] ['ticket_name'] = $v ['name'];
					$entertainmentres [$k] ['ticket_price'] = $v ['price'];
					$entertainmentres [$k] ['ticket_deadline'] = $v ['deadline'];
					$entertainmentres [$k] ['ticket_original'] = $v ['original'];
					$entertainmentres [$k] ['ticket_image'] = $v ['image'];
					$entertainmentres [$k] ['scenic_image'] = $v ['scenic_image'];
					$entertainmentres [$k] ['scenic_id'] = $v ['scenic_id'];
					$entertainmentres [$k] ['scenic_name'] = $v ['scenic_name'];
					$entertainmentres [$k] ['scenic_address'] = $v ['scenic_address'];
					$entertainmentres [$k] ['scenic_latitude'] = $v ['scenic_latitude'];
					$entertainmentres [$k] ['scenic_longitude'] = $v ['scenic_longitude'];
					$entertainmentres [$k] ['scenic_phone'] = $v ['scenic_phone'];
				}
				$json ['result'] = "0";
				$json ['msg'] = "获取成功";
				$json ['publish'] = $result;
				$json ['scenic'] = $scenic;
				$json ['ticket'] = $ticketres;
				$json ['entertainment'] = $entertainmentres;
				$this->ajaxReturn ( $json );
			} else {
				$this->ajaxReturn ( array (
						'msg' => '没有更多的信息了',
						'result' => '-1' 
				), 'json' );
			}
		} else {
			$this->ajaxReturn ( array (
					'msg' => '失败，数据不是以POST方式提交',
					'result' => '-2' 
			), 'json' );
		}
	}
	
	// 加载更多约吧信息，加了缓存，每次加载十条
	/*
	 * public function getPublish() {
	 * $page_num = I ( 'page_num' );
	 * $publish = D ( 'PublishView' );
	 * if ($page_num != null || $page_num != '') {
	 * // file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
	 * $start = $page_num * 10;
	 * $end = $page_num + 10;
	 * if (! $result = S ( 'result' )) {
	 * $result = $publish->order ( array (
	 * 'ctime' => 'desc'
	 * ) )->select ();
	 * S ( 'result', $result, 600 );
	 * }
	 * $json ['result'] = "0";
	 * $json ['msg'] = "获取成功";
	 * $res = array_slice ( $result, $start, 10 );
	 * foreach ( $res as $k => $v ) {
	 * $res [$k] ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
	 * }
	 * $json ['publish'] = $res;
	 *
	 * if (sizeof ( $json ['publish'] ) > 0) {
	 * $this->ajaxReturn ( $json );
	 * } else {
	 * $this->ajaxReturn ( array (
	 * 'msg' => '没有更多的信息了',
	 * 'result' => '-1'
	 * ), 'json' );
	 * }
	 * } else {
	 * $this->ajaxReturn ( array (
	 * 'msg' => '失败，没有传递正确的标签',
	 * 'result' => '-2'
	 * ), 'json' );
	 * }
	 * }
	 */
	public function getByTag() {
		if (IS_POST) {
			$page_num = I ( 'page_num' );
			if ($page_num == 0) {
				S ( 'tresult', null );
			}
			$publish = D ( 'PublishView' );
			$tag = I ( "tag" );
			// if(!$tresult = S('tresult')){
			$tresult = $publish->where ( array (
					'tag' => $tag 
			) )->order ( array (
					'ctime' => 'desc' 
			) )->select ();
			// S('tresult',$tresult,600);
			// }
			$start = $page_num * 10;
			if (sizeof ( $tresult ) > 0) {
				$res = array_slice ( $tresult, $start, 10 );
				foreach ( $res as $k => $v ) {
					$res [$k] ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
				}
				$json ['result'] = "0";
				$json ['msg'] = "获取成功";
				$json ['publish'] = $res;
				$this->ajaxReturn ( $json );
			} else {
				$this->ajaxReturn ( array (
						'msg' => '没有更多的信息了',
						'result' => '-1' 
				), 'json' );
			}
		} else {
			$this->ajaxReturn ( array (
					'msg' => '失败，没有传递正确的标签',
					'result' => '-2' 
			), 'json' );
		}
	}
	public function myPublish() {
		$publish = D ( 'PublishView' );
		if (IS_POST) {
			$uid = $_POST ['id'];
			$result = $publish->where ( array (
					'uid' => $uid 
			) )->order ( array (
					'ctime' => 'desc' 
			) )->select ();
			foreach ( $result as $k => $v ) {
				$result [$k] ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
			}
			if (sizeof ( $result ) > 0) {
				$json ['result'] = "0";
				$json ['msg'] = "获取成功";
				$json ['publish'] = $result;
				$this->ajaxReturn ( $json );
			} else {
				$this->ajaxReturn ( array (
						'msg' => '没有更多的信息了',
						'result' => '-1' 
				), 'json' );
			}
		} else {
			$this->ajaxReturn ( array (
					'msg' => '失败，数据不是以POST方式提交',
					'result' => '-2' 
			), 'json' );
		}
	}
	public function getByID() {
		$publish = D ( 'PublishView' );
		if (IS_POST) {
			$pid = $_POST ['pid'];
			$result = $publish->where ( array (
					'id' => $pid 
			) )->find ();
			$result ['ctime'] = date ( 'Y-m-d H:i:s', $v ['ctime'] );
			if (sizeof ( $result ) > 0) {
				$json ['result'] = "0";
				$json ['msg'] = "获取成功";
				$json ['publish'] = $result;
				$this->ajaxReturn ( $json );
			} else {
				$this->ajaxReturn ( array (
						'msg' => '没有更多的信息了',
						'result' => '-1' 
				), 'json' );
			}
		} else {
			$this->ajaxReturn ( array (
					'msg' => '失败，数据不是以POST方式提交',
					'result' => '-2' 
			), 'json' );
		}
	}
	public function downloads() {
		$name_tmp = explode ( "_", 'tubu-1.0.0.apk' );
		$type = $name_tmp [0];
		$file_time = explode ( ".", $name_tmp [3] );
		$file_time = $file_time [0];
		$file_date = date ( "Y/md", $file_time );
		$downloadpath = "Public/download/";
		$file_dir = $downloadpath;
		
		if (! file_exists ( $file_dir . 'tubu-1.0.0.apk' )) {
			header ( "Content-type: text/html; charset=utf-8" );
			echo "File not found!";
			exit ();
		} else {
			$file = fopen ( $file_dir . 'tubu-1.0.0.apk', "r" );
			Header ( "Content-type: application/octet-stream" );
			Header ( "Accept-Ranges: bytes" );
			Header ( "Accept-Length: " . filesize ( $file_dir . 'tubu-1.0.0.apk' ) );
			Header ( "Content-Disposition: attachment; filename=" . 'tubu-1.0.0.apk' );
			echo fread ( $file, filesize ( $file_dir . 'tubu-1.0.0.apk' ) );
			fclose ( $file );
		}
	}
}